'''
Created on Jan 26, 2011

@author: mikeg
'''

import sqlite3
from multiprocessing import Pipe, Pool, Process
import time

# Create sqlite3 connection and cursor
# Retuns both a connection and cursor
def setup_sqlite(file):
    conn = sqlite3.connect(file)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()
    return conn, cur

# Pass this function the open connection and cursor to reuse them
# Checks to see if table 'log' exists. If it does don't do anything.
# If it doesn't, create a table named 'log'.
def init_table(conn, cursor):
    cursor.execute("select sql from sqlite_master where name = 'log'")
    print "DEBUG: CHECKING FOR LOG TABLE"
    if(cursor.fetchone() is None):
        print "DEBUG: LOG TABLE NOT FOUND"
        cursor.execute('''create table log (date text, method text, time text)''')
        conn.commit()
    else:
        print "DEBUG: LOG TABLE EXISTS"
    return None

# Insert a row into the table. Pass connection and cursor to the function
# to reuse them.
def write_entry(conn, cursor, date, name, time):
    cursor.execute('''INSERT INTO log(date, method, time) VALUES (?, ?, ?)''', (date, name, time))
    conn.commit()

# Kill the sqlite3 connection and cursor
def kill_sqlite3(conn, cursor):
    cursor.close()
    conn.close()

def debug_log_table(conn,cursor):
    return cursor.execute('''select * from log''')
    
def open_pipe():
    a, b = Pipe()
    return a, b 

def sendatob(a,b, message):
    a.send(message)
    return b.recv()

def sendbtoa(b,a, message):
    b.send(message)
    return a.recv()
    
def proc_test():
    time_proc = time.time()
    a,b = open_pipe()
    pa = Process(target=sendatob, args=(a, b, 'gtfo'))
    pb = Process(target=sendbtoa, args=(b, a, 'stfu'))
    pa.start()
    pa.join()
    pb.start()
    pb.join()
    time_temp = (time.time()-time_proc)*1000
    print 'Process time = ', time_temp, ' (ms)'
    return time_temp
    
if __name__ == '__main__':
    conn, cursor = setup_sqlite('sqlite3.db')
    init_table(conn, cursor)
    
    time_pipe = time.time()
    a, b = open_pipe()
    sendatob(a,b,'gtfo')
    sendbtoa(b,a,'stfu')
    temp_time = (time.time() - time_pipe)*1000
    thyme = time.time()
    write_entry(conn, cursor, thyme, "pipe", temp_time)
    print 'Pipe time = ', (time.time() - time_pipe)*1000, ' (ms)'
        
    time_seq = time.time()
    f = open('/dev/null', "w")
    f.write('gtfo')
    f.write('stfu')
    f.close()
    thyme = time.time()
    temp_time = (time.time() - time_seq)*1000
    write_entry(conn, cursor, thyme, "seq", temp_time)
    print 'Seq time = ', (time.time() - time_seq)*1000, ' (ms)'
    
    thyme = time.time()
    temp_time = proc_test()
    write_entry(conn, cursor, thyme, "proc", temp_time)
    
    for row in debug_log_table(conn, cursor):
        print row[0], "\t|",row[1], "\t|", row[2]
    
    kill_sqlite3(conn, cursor)   
    
